package com.pg.utils;

import org.postgresql.PGConnection;
import org.postgresql.largeobject.LargeObject;
import org.postgresql.largeobject.LargeObjectManager;
import org.springframework.beans.factory.annotation.Autowired;

import javax.xml.ws.Action;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Base64;

/**
 * 传输图片
 *
 * @author L
 *
 */
public class UploadFileUtils {

//    @Autowired
//    private static Connection conn;

    /**
     * 将文件字符串转largeObject 存到pg中
     *
     * @param base64 base64
     * @return oid
     * @throws Exception
     */
    public static String uploadFiles(String base64) {
        try {
            Connection conn = JdbcUtils.getConnection();
            conn.setAutoCommit(Boolean.FALSE);
            LargeObjectManager lobj = conn.unwrap(PGConnection.class).getLargeObjectAPI();
            long oid = lobj.createLO(LargeObjectManager.READ | LargeObjectManager.WRITE);
            LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
//		byte[] byteArray = Base64.getDecoder().decode(base64);
            byte[] byteArray = Base64.getMimeDecoder().decode(base64);
            obj.write(byteArray);
            obj.close();
            conn.commit();
            JdbcUtils.close(null, conn);
            return oid + "";
        } catch (SQLException e) {
            e.printStackTrace();
            return "";
        }
    }

}
